#include <vector>
#include <utility>
#include <string>
#include "article.h"
#include "newsgroup.h"
#include "dbinmemory.h"
#include <algorithm>
using namespace std;

dbinmemory::dbinmemory(){
	nextgroupid = 0;
}

//ok
vector<pair<int, string>> dbinmemory::listnewsgroups(){
	vector<pair<int, string>> result;
	for(auto it = newsgroups.begin(); it != newsgroups.end(); ++it){
		result.push_back(make_pair(it->first, (it->second).gettitle()));
	}
	sort(result.begin(), result.end(), [](const pair<int,string>& p1, const pair<int,string>& p2){return p1.first < p2.first;});
	return result;
	
}
//ok
bool dbinmemory::createnewsgroup(string name){
	auto it = newsgroups.begin();
	for(; it != newsgroups.end(); ++it){
		if((it->second).gettitle()==name){
			break;
		}
	}
	if(it != newsgroups.end()){
		return false;
	}
	
	newsgroups.insert(make_pair(++nextgroupid, newsgroup(nextgroupid, name)));
	return true;
}

//OK
bool dbinmemory::deletenewsgroup(int groupid){
	return newsgroups.erase(groupid);
}

//OK
pair<vector<pair<int, string>>, int> dbinmemory::listarticles(int groupid){
	vector<pair<int, string>> result;
	int status = 1; //0 = newsgroup exists. 1 = does not exist
	auto it = newsgroups.find(groupid);
	if(it != newsgroups.end()){
		result = (it->second).getarticlenames();
		status = 0; 
	}
	sort(result.begin(), result.end(), [](const pair<int,string>& p1, const pair<int,string>& p2){return p1.first < p2.first;});
	return make_pair(result, status);
}

//OK
bool dbinmemory::createarticle(int groupid, string title, string author, string text){
	auto it = newsgroups.find(groupid);
	if(it==newsgroups.end()){
		return false; //group not found. return false
	}
	
	(it->second).addarticle(title, author, text);
	return true;
}

//Seems to work as long as indices are working (see below)
int dbinmemory::deletearticle(int groupid, int articleid){
	auto it = newsgroups.find(groupid);
	if(it==newsgroups.end()){
		return 1; //group not found. return 1
	}
	if(!((it->second).deletearticle(articleid))){
		return 2; //article not found
	}
	return 0;
}

//Something is buggy here, with indexing
pair<int, article> dbinmemory::getarticle(int groupid, int articleid){
	auto it = newsgroups.find(groupid);
	article a(0, "","","");
	if(it==newsgroups.end()){
		return make_pair(1, a); //group not found. return false
	}
	return (it->second).getarticle(articleid); //Has to cover all cases, both article found and not found, and make a pair to return with indication number (0,1,2) and the article, NOT an article ID.
	
	
}

	
